#!/usr/bin/env python
import sys
if sys.version_info < (2, 7):
    raise SystemError("must use python 2.7 or greater")

def process_xpath(xml, xpath):
    """Returns the result of this xpath query on the given xml string
    
    >>> process_xpath('<foo></foo>', '//bar')
    []
    >>> process_xpath('<html><head><title>my happy test</title></head></html>', '//title')
    ['<title>my happy test</title>']
    >>> process_xpath('<foo><bar><a><b></b></a></bar><bar></bar></foo>', '//bar[a]')
    ['<bar><a><b/></a></bar>']
    """
    from lxml import etree

    tree = etree.XML(xml)
    return [etree.tostring(c) for c in tree.xpath(xpath)]

if __name__ == "__main__":  
    import argparse
    parser = argparse.ArgumentParser(add_help=True)
    parser.add_argument('--version', action='version', version='%(prog)s 1.0')
    
    group_xml = parser.add_mutually_exclusive_group(required=True)
    group_xml.add_argument('-x', action='store', dest='xml',
                    help='XML Content to be queried')
    group_xml.add_argument('--xmlfile', dest='xmlfile', 
                    type=argparse.FileType('rt'),
                    help='XML File to read the content from')
    
    group_xp = parser.add_mutually_exclusive_group(required=True)
    group_xp.add_argument('-q', action='store', dest='xpath',
                    help='XPath query')
    
    args = parser.parse_args()
    xml = args.xml or args.xmlfile.read()
    xpath = args.xpath
    
    ret = process_xpath(xml, xpath)
    for r in ret:
        print r

import doctest, unittest
class ModuleUnitTesting(unittest.TestCase):
        
    def test_py_xpath(self):
        suite = doctest.DocTestSuite('py_xpath')
        testRunner = unittest.TextTestRunner()
        testRunner.run(suite)